<script setup>
import CommonSelect from "@/components/commonSelect.vue";
import FlowDefForm from "./FlowDefForm.vue";
import { useMessage, useMessageBox } from "@/hooks/message";

const emit = defineEmits(["reload-flow"]);
const _value = defineModel();
const flowDef = defineModel("flowDef");

const flowDefFormRef = ref(null);

const data = reactive({
  defFlowId: "",
  defFlow: {
    id: "",
    flowName: "未命名流程",
    flowKey: "",
    icon: {
      name: "file-icons:omnigraffle",
      bgc: "#4C87F3",
      color: "#FFFFFF"
    },
    formId: "",
    formName: "",
    status: "-1",
    version: 1,
    groupId: "1",
    remark: null,
    flowDef: ""
  }
});

onMounted(() => {
  data.defFlowId = _value.id;
});

const handleDefFlowChange = (id, item) => {
  data.defFlow = item;
};

const handleLoadFlow = async () => {
  if (!data.defFlowId) {
    useMessage().warning("请先选择已有流程");
    return;
  }
  if (!data.defFlow) {
    useMessage().warning("流程数据不存在");
    return;
  }
  useMessageBox()
    .confirm(`以${data.defFlow.flowKey}为模板加载流程`)
    .then(() => {
      _value.value.icon = JSON.parse(data.defFlow.flowIcon);
      _value.value.formId = data.defFlow.formId;
      _value.value.formName = data.defFlow.formName;
      _value.value.groupId = data.defFlow.groupId;
      _value.value.remark = data.defFlow.remark;
      _value.value.flowDef = data.defFlow.flowDef;
      flowDef.value = JSON.parse(data.defFlow.flowDef);
    });
};

const validate = () => {
  return flowDefFormRef.value.validate();
};

defineExpose({ validate });
</script>

<template>
  <div class="flow-attr">
    <FlowDefForm ref="flowDefFormRef" v-model:defFlow="_value">
      <template #itemLoad>
        <el-form-item label="已有流程">
          <div style="display: flex">
            <CommonSelect
              v-model:defaultValue="data.defFlowId"
              label="flowName,version"
              value="id"
              url="/esflow/def/getlist"
              auto-query
              @change="handleDefFlowChange"
            />
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="handleLoadFlow"
            >
              加载模板
            </el-button>
          </div>
        </el-form-item>
      </template>
    </FlowDefForm>
  </div>
</template>

<style scoped></style>
